package com.food.eat.controller;

import com.food.eat.dto.UsersDto;
import com.food.eat.pojo.Users;
import com.food.eat.pojo.bo.UserBO;
import com.food.eat.pojo.vo.UserVo;
import com.food.eat.service.UserService;
import com.food.eat.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;


/**
 * @Author:RenPu
 * @Date: 2020/7/19 12:34
 * @Version: 1.0
 * @description:
 */

@Api(value = "用户模块的控制层", tags = "用于用户注册以及校验的接口")
@RestController
@RequestMapping("/passport")
public class PassPortController extends BaseController {


    //日志记录
    final static Logger logger = LoggerFactory.getLogger(PassPortController.class);

    @Resource
    private UserService userService;


    @Resource
    private RedisOperator redisOperator;


    @ApiOperation(value = "用户的校验名称是否存的接口", httpMethod = "GET", notes = "用户的校验名称是否存的接口")
    @GetMapping("/usernameIsExist")
    public FoodResultJson usernameIsExist(@RequestParam String username) {

        //判断用户名称是否为空值
        if (StringUtils.isBlank(username)) {
            return FoodResultJson.errMsg("用户名称不能为空");
        }

        logger.info("--------------************O(∩_∩)O哈哈~");


        //查找用户名称是否存在
        boolean isExist = userService.queryUserName(username);

        if (isExist) {
            return FoodResultJson.errMsg("用户名称已经存在！！！！！");
        }

        //用户名称未重复，注册成功！！
        return FoodResultJson.ok();

    }


    @ApiOperation(value = "用户的注册的接口", httpMethod = "POST", notes = "用户的注册的接口")
    @PostMapping("/regist")
    public FoodResultJson regist(@RequestBody UserBO userBO, HttpServletRequest request, HttpServletResponse response) {

        String username = userBO.getUsername();

        String confirmPassword = userBO.getConfirmPassword();

        String password = userBO.getPassword();

        //判断是否为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(confirmPassword) || StringUtils.isBlank(password)) {

            return FoodResultJson.errMsg("用户名称或者密码不允许为空");
        }

        // 查找用户名称是否存在
        boolean isExist = userService.queryUserName(username);

        if (isExist) {
            return FoodResultJson.errMsg("用户名称已经存在");
        }


        //密码长度是否满足6位

        if (password.length() < 6) {

            return FoodResultJson.errMsg("密码长度不允许小于6");

        }


        //俩次输入的密码是否一致

        if (!password.equals(confirmPassword)) {
            return FoodResultJson.errMsg("俩次输入的密码不一致");

        }


        //完成用户信息的注册
        Users users = userService.createUser(userBO);


        //TODO 实现注册时生成用户的redis会话
        UserVo userVo = getUserVo(users);


        //将数据封装到cookie,响应给前台便于数据的渲染，isEncode:设置是否需要加密
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userVo), true);


        return FoodResultJson.ok();

    }


    /**
     * 实现注册时成用户的redis会话方法的封装
     *
     * @param users
     * @return
     */
    public UserVo getUserVo(Users users) {

        String uniqueToken = UUID.randomUUID().toString().trim();
        redisOperator.set(REDIS_USER_TOKEN + ":" + users.getId(), uniqueToken);

//        //调用方法将用户的一些隐私信息，进行隐藏
//        users=setNullUserProperty(users);

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(users, userVo);
        userVo.setUserUniqueToken(uniqueToken);

        return userVo;

    }


    @ApiOperation(value = "用户登录接口", httpMethod = "POST", notes = "用户登录接口")
    @PostMapping("/login")
    public FoodResultJson login(@RequestBody UserBO userBO, HttpServletRequest request, HttpServletResponse response) throws NoSuchAlgorithmException {

        String username = userBO.getUsername();
        String password = userBO.getPassword();
        //判断是否为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return FoodResultJson.errMsg("用户名称或者密码不允许为空");
        }

        Users users = userService.login(username, MD5Util.getMD5Str(password));

        if (users == null) {
            return FoodResultJson.errMsg("用户账号或者密码输入有误");
        }


//        //调用方法将用户的一些隐私信息，进行隐藏
//        users=setNullUserProperty(users);

        //将数据封装到cookie,响应给前台便于数据的渲染，isEncode:设置是否需要加密
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(users), true);

        //TODO 用户生成token,存入redis会话
        UserVo userVo = getUserVo(users);
        //TODO 同步购物车数据
        return FoodResultJson.ok(userVo);

    }


    /**
     * 将用户比较敏感的信息，进行设置为空进行保护
     *
     * @param userResult
     * @return
     */
    private Users setNullUserProperty(Users userResult) {
        userResult.setRealname(null);
        userResult.setCreatedTime(null);
        userResult.setPassword(null);
        userResult.setUpdatedTime(null);
        userResult.setBirthday(null);
        userResult.setEmail(null);
        userResult.setMobile(null);

        return userResult;
    }


    @ApiOperation(value = "用户退出接口", httpMethod = "POST", notes = "用户退出接口")
    @PostMapping("/logout")
    public FoodResultJson logout(@RequestParam String userId,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        CookieUtils.deleteCookie(request, response, "user");   //这的user名称，要和存储在cookie的cookiename的值保持一致

        //用户退出清理redis用户的会话信息
        redisOperator.del(REDIS_USER_TOKEN + ":" + userId);

        return FoodResultJson.ok();

    }



    @ApiOperation(value = "测试充血模型行为能力-ModelOne", httpMethod = "GET", notes = "测试充血模型行为能力-ModelOne")
    @GetMapping("/testModelAbilityModelOne")
    public FoodResultJson testModelAbilityModelOne(String username){
        return FoodResultJson.ok(UsersDto.queryUserName(username));
    }




    @ApiOperation(value = "测试充血模型行为能力-ModelTwo", httpMethod = "GET", notes = "测试充血模型行为能力-ModelTwo")
    @GetMapping("/testModelAbilityModelTwo")
    public FoodResultJson testModelAbilityModelTwo(String username){
        return FoodResultJson.ok(userService.queryUserNameModel(username));
    }




}
